#!/bin/bash

SHELL_DIR="$(cd $(dirname $0); pwd)"
PROJECT_DIR=$1
SYSTEM_DIR=$2
system_folder_name=`ls *system* -d`
if [[ ! -d ${SYSTEM_DIR} ]]; then
	echo "无SYSTEM目录，爪巴！"
	exit 1
fi
if [[ -f $SHELL_DIR/Insides/apktool/apktool.jar ]]; then
	ApkTool="java -jar $SHELL_DIR/Insides/apktool/apktool.jar" 
	echo "ApkTool version:`$ApkTool -version`"
	
else
	echo "Not found ApkTool"
	
fi

c=1
all_list=`ls -d */`
for list in $all_list
do 
	size=`du -s -b $PROJECT_DIR/$list | awk '{print $1}'`
	if [[ $list == "TI_config/" || $list == "TI_out/" ]];then
		echo "$c. $list 是工具目錄不檢查"
	elif [[ $list == "system/" ]];then
		echo "$c. $list ${size} Bytes"
		while read apkname;
		do
			if [[ $apkname != "" ]];then
				echo "    預計在此目錄內刪除$apkname App"
				delapp_path=`find $SYSTEM_DIR/app -name "$apkname"`
				if [[ $delapp_path != "" ]];then
					echo -e "\033[32m$delapp_path\033[0m"
					rm -r $delapp_path
				else
					echo -e "\033[33m    => $apkname is not found\033[0m"
				fi
				delapp_path=""
			fi
		done <  $SHELL_DIR/rm.txt
		
	else
		if [[ $size -lt 52428800 ]];then
		echo "$c. $list $sizeM"
			echo -e "\033[33m    => This partitions size is small, skip\033[0m"
			#break
		else
			echo "$c. $list ${size} Bytes"
			while read apkname;
			do	
			if [[ $apkname != "" ]];then
				echo "    預計在此目錄內刪除$apkname App"
				delapp_path=`find $PROJECT_DIR/$list -name "$apkname"`
				if [[ $delapp_path != "" ]];then
					echo -e "\033[32m    $delapp_path\033[0m"
					rm -r $delapp_path
					if [[ -f $PROJECT_DIR/$list/apkcerts.txt ]];then
						sed -i '/'"$apkname"'/d' $PROJECT_DIR/$list/apkcerts.txt
					fi
					if [[ -f $PROJECT_DIR/$list/applist/applist.txt ]];then
						sed -i '/'"$apkname"'/d' $PROJECT_DIR/$list/applist/applist.txt
					fi
					
				else
					echo -e "\033[33m    => $apkname is not found\033[0m"
				fi
				delapp_path=""
			fi
		done <  $SHELL_DIR/rm.txt
		fi	
		
	fi
	c=$(($c+1))
done

sleep 10
